package vip.ola.pay.channel.ymzfb;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.entity.PayOrder;
import vip.ola.core.entity.PayPassageAccount;
import vip.ola.pay.channel.dszfb.DszfbPaymentService;
import vip.ola.pay.channel.ymwxpay.YMSignUtils;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchPay;
import vip.ola.pay.service.RpcCommonService;

import java.util.Map;

import static vip.ola.core.common.constant.PayConstant.PAY_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.PAY_STATUS_SUCCESS;

@RequestMapping("/api/ymzfbpay")
@Controller
public class YmzfbPayController extends BaseController {

    private static final MyLog _log = MyLog.getLog(YmzfbPayController.class);

    @Autowired
    private RpcCommonService rpcCommonService;
    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    @PostMapping("/notify")
    @ResponseBody
    public String notify(@RequestParam Map<String, String> data){
        _log.info("接收ympay回调：" + data);
        String bizContent = data.get("biz_content");
        _log.info("接收ympay回调bizContent->{}：" + bizContent);
        JSONObject bizContentMap = JSONObject.parseObject(bizContent);
        String payOrderId = bizContentMap.getString("out_trade_no");
        PayOrder payOrder = this.rpcCommonService.rpcPayOrderService.findByPayOrderId(payOrderId);
        if (payOrder == null) {
            return "order not exist!";
        }
        if ((payOrder.getStatus().byteValue() == 2) || (payOrder.getStatus().byteValue() == 3)) {
            return "success";
        }
        PayPassageAccount payPassageAccount = this.rpcCommonService.rpcPayPassageAccountService.findById(payOrder.getPassageAccountId());
        if ((payPassageAccount == null) || (StringUtils.isBlank(payPassageAccount.getParam()))) {
            return "fail";
        }
        String retSign = bizContentMap.getString("sign");
        Map jsonMap = JSONObject.toJavaObject(bizContentMap, Map.class);
        jsonMap.remove("sign");
        String sign = YMSignUtils.sign(jsonMap, payPassageAccount.getPrivateKey());
        _log.info("加签信息,sign=：" + sign);
        if (retSign.equals(sign)) {
            int result = this.rpcCommonService.rpcPayOrderService.updateStatus4Success(payOrder.getPayOrderId());
            _log.info("更新订单状态为支付成功: result={}", new Object[] { Integer.valueOf(result) });
            if (result == 1)
            {
                this.baseNotify4MchPay.doNotify(payOrder, true);
                return "success";
            }
        }
        return "fail!";
    }
}
